package com.atguigu.tingshu.common.service.impl;

import com.atguigu.tingshu.common.config.minio.MinioConstantProperties;
import com.atguigu.tingshu.common.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.MD5;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.StatObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@Slf4j
public class FileUpLoadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Override
    public String fileUpload(MultipartFile file) {
        if (file == null)
            throw new GuiguException(201, "上传文件为空");
        String objectName = "";
        try {
            byte[] fileBytes = file.getBytes();
            String prefix = MD5.encrypt(new String(fileBytes));
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            objectName = prefix + suffix;

            // 先判断文件是否存在
            StatObjectArgs.Builder builder = StatObjectArgs.builder();
            StatObjectArgs statObjectArgs = builder.bucket(minioConstantProperties.getBucketName())
                    .object(objectName)
                    .build();
            minioClient.statObject(statObjectArgs);// 这个方法，如果文件不存在，则抛异常
            // 文件存在，直接返回
            return minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + "/" + objectName;
        } catch (IOException e) {
            log.error("上传文件失败{}", e.getMessage());
            throw new GuiguException(201, "上传文件失败");
        } catch (Exception e) {
            try {
                // minio中没有，上传
                PutObjectArgs.Builder builder = PutObjectArgs.builder();
                PutObjectArgs putObjectArgs = builder.bucket(minioConstantProperties.getBucketName())
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .build();
                minioClient.putObject(putObjectArgs);
                return minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + "/" + objectName;
            } catch (Exception ex) {
                log.error("上传文件到minio失败{}", ex.getMessage());
                throw new GuiguException(201, "上传文件到minio失败");
            }
        }
    }
}
